package czk.concrent.producerAndConsumer;

import java.util.LinkedList;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/5/30 21:04
 */
public class Test {
    public static void main(String[] args) throws InterruptedException {
        MessageQueue messageQueue=new MessageQueue(3);
        for (int i = 0; i <5 ; i++) {
            int id=i;
            new Thread(()->{
                messageQueue.put(new Message(id+1,"消息"+(id+1)));
            },"生产者"+i+1).start();
        }
        while (true){
            Thread.sleep(1*1000);
            new Thread(()->{
                Message message = messageQueue.get();
                System.out.println(message);
            },"消费者").start();
        }
        }

}
class MessageQueue{
    // 存消息集合
    private LinkedList<Message> linkedList=new LinkedList<>();
    // 队列的容量
    private int capCity;

    public MessageQueue(int capCity) {
        this.capCity = capCity;
    }

    // 取到消息
    public Message get(){
        // 判断队列是否为空
        synchronized (linkedList){
            while (linkedList.isEmpty()){
                try {
                    System.out.println("队列为空，等待");
                    linkedList.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 从队列的头部获取元素
            linkedList.notifyAll();
        }

        return linkedList.removeFirst();
    }
    // 存消息
    public void put(Message message){
        synchronized (linkedList){
            // 检查容量是否满了
            while (linkedList.size()==capCity){
                // 进入队列的waitSet
                try {
                    System.out.println("队列已经满了，不能生产了");
                    linkedList.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            linkedList.addLast(message);
            linkedList.notifyAll();
        }
    }
}
